package com.isoft.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.isoft.entity.FlightInfo;
import com.isoft.result.R;
import com.isoft.service.FlightInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("api/flightInfo")
public class FlightInfoController {

    @Autowired
    private FlightInfoService flightInfoService;

    // 新增
    @PostMapping
    public R add(@RequestBody FlightInfo flightInfo) {
        boolean saved = flightInfoService.save(flightInfo);
        return saved ? R.ok("新增成功") : R.error("新增失败");
    }

    // 删除
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Long id) {
        boolean removed = flightInfoService.removeById(id);
        return removed ? R.ok("删除成功") : R.error("删除失败");
    }

    // 修改
    @PutMapping
    public R update(@RequestBody FlightInfo flightInfo) {
        boolean updated = flightInfoService.updateById(flightInfo);
        return updated ? R.ok("修改成功") : R.error("修改失败");
    }

    // 查询单条
    @GetMapping("/{id}")
    public R get(@PathVariable Long id) {
        FlightInfo info = flightInfoService.getById(id);
        return info != null ? R.ok(info) : R.error("未找到数据");
    }

    // 分页查询
    @GetMapping("/list")
    public R list(
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String flightNumber,
            @RequestParam(required = false) String aircraftNumber,
            @RequestParam(required = false) String aircraftType
    ) {
        Page<FlightInfo> page = new Page<>(pageNo, pageSize);
        QueryWrapper<FlightInfo> queryWrapper = new QueryWrapper<>();
        if (flightNumber != null && !flightNumber.isEmpty()) {
            queryWrapper.like("flight_number", flightNumber);
        }
        if (aircraftNumber != null && !aircraftNumber.isEmpty()) {
            queryWrapper.like("aircraft_number", aircraftNumber);
        }
        if (aircraftType != null && !aircraftType.isEmpty()) {
            queryWrapper.like("aircraft_type", aircraftType);
        }
        queryWrapper.orderByDesc("create_time");
        Page<FlightInfo> result = flightInfoService.page(page, queryWrapper);
        return R.ok(result);
    }
}